package map;

import org.junit.Test;

import java.security.Principal;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Summerday
 */
public class TestMap {


    Map<Integer, String> map = new HashMap<>();

    {
        map.put(1, "hello");
        map.put(2, "summer");
        map.put(3, "day");
        map.put(4, "tqbx");
    }

    private void print(Map<Integer, String> map) {
        map.forEach((x, y) -> {
            System.out.println("x -> " + x + ", y -> " + y);
        });
    }

    @Test
    public void testForEach() {
        map.forEach((x, y) -> {
            System.out.println("x -> " + x + ", y -> " + y);
        });
    }

    @Test
    public void testRemove() {
        map.remove(3, "day");
        print(map);
    }

    @Test
    public void testCompute() {
        //key==2 对应的value存在时，使用计算的结果作为新value
        map.computeIfPresent(2, (k, v) -> v.toUpperCase());
        print(map);

        //key==6 对应的value为null (或不存在)时，使用计算的结果作为新value
        map.computeIfAbsent(6, (k) -> k + "haha");
        print(map);
    }

    @Test
    public void testGetOrDefault(){
        String value = map.getOrDefault(5, "如果没有key==5的value,就返回这条信息");
        System.out.println(value);
    }

    @Test
    public void testMerge(){
        // key为2 的值 加上 +add
        map.merge(2," + add",(oldval, newVal) -> oldval + newVal);
        print(map);
    }

    @Test
    public void testPutIfAbsent(){
        String s1 = map.putIfAbsent(10, "101010");
        System.out.println(s1);
        print(map);
        System.out.println("============================");
        String s2 = map.putIfAbsent(2, "2222");
        System.out.println(s2);
        print(map);
    }

    @Test
    public void testReplace(){
        map.replace(1,"hello","hi");
        print(map);
        System.out.println("============================");
        map.replace(2,"天乔巴夏");
        print(map);
        System.out.println("============================");
        map.replaceAll((k,v)-> k + "-" + v.toUpperCase());
        print(map);
    }
}
